package com.jeejio.train.controller;

import com.jeejio.train.entity.Course;
import com.jeejio.train.entity.Lecturer;
import com.jeejio.train.service.CourseService;
import com.jeejio.train.util.IConstant;
import com.jeejio.train.util.UserException;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/course")
public class CourseController {
    private static final Logger LOG = LoggerFactory.getLogger(CourseController.class);

    @Autowired
    private CourseService courseService = null;

    @Autowired
    private HttpServletRequest httpServletRequest = null;

    @RequestMapping("/create")
    public String create(@RequestParam("datetime") String datetime
            , @RequestParam("title") String title
            , @RequestParam(value = "address", required = false) String address
            , @RequestParam(value = "draft", required = false) Integer draft) {
        JSONObject jResult = new JSONObject();
        try {
            Lecturer lecturer = (Lecturer) httpServletRequest.getSession()
                    .getAttribute(IConstant.KEY_SESSION_USER);
            Course course = new Course();
            course.setTitle(title);
            course.setLecturer(lecturer);
            course.setAddress(address);
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date = dateFormat.parse(datetime);
            course.setDeliveryTime(date);
            course.setDraft((byte) ((null == draft) || (0 == draft) ? 0x0 : 0x1));
            course.setCreateTime(new Date(System.currentTimeMillis()));
            course.setModifyTime(null);

            if (courseService.create(course)) {
                jResult.put("state", IConstant.SUCCESS);
                jResult.put("msg", "创建成功");
            } else {
                jResult.put("state", IConstant.E_COURSE_CREATE);
                jResult.put("msg", "创建失败");
            }
        } catch (ParseException e) {
            LOG.error(e.getMessage(), e);
            jResult.put("state", IConstant.E_COURSE_CREATE);
            jResult.put("msg", "时间无效");
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            jResult.put("state", IConstant.E_COURSE_CREATE);
            jResult.put("msg", "服务器内部错误，请联系系统管理员");
        }
        return jResult.toString();
    }

    /**
     * 查询日期的讲座列表
     * @param queryDate
     * @param draft
     * @return
     */
    @RequestMapping("/findByDeliveryDate")
    public String findByDeliveryDate(@RequestParam("date") String queryDate
            , @RequestParam("draft") Integer draft) {
        JSONObject jResult = new JSONObject();
        try {
            Lecturer lecturer = null;
            HttpSession session = httpServletRequest.getSession();
            if (null != session) {
                lecturer = (Lecturer) session.getAttribute(IConstant.KEY_SESSION_USER);
            }

            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            Date date = dateFormat.parse(queryDate);
            JSONArray jsonArray = new JSONArray();
            List<Course> courseList = courseService.findByDeliveryDate(date, draft.byteValue());
            for (Course course : courseList) {
                JSONObject jCourse = new JSONObject();
                jCourse.put("id", course.getId());
                jCourse.put("title", course.getTitle());
                jCourse.put("lecturer_id", course.getLecturer().getId());
                jCourse.put("lecturer_full_name", course.getLecturer().getFullName());
                jCourse.put("address", course.getAddress());
                SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss");
                jCourse.put("delivery_time", timeFormat.format(course.getDeliveryTime()));
                jCourse.put("draft", course.getDraft());

                if ((null != lecturer)
                        && (lecturer.getId() == course.getLecturer().getId())) { // 属于当前用户的讲座
                    jCourse.put("allow_edit", true); // 允许编辑
                    if (0 != course.getDraft()) {
                        jCourse.put("allow_draft", true); // 允许存为草稿
                    } else {
                        jCourse.put("allow_draft", false);
                    }
                } else {
                    jCourse.put("allow_edit", false);
                }

                jsonArray.put(jCourse);
            }
            jResult.put("courses", jsonArray);
            jResult.put("state", IConstant.SUCCESS);
        } catch (ParseException e) {
            LOG.error(e.getMessage(), e);
            jResult.put("state", IConstant.E_COURSE_FIND);
            jResult.put("msg", "时间无效");
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            jResult.put("state", IConstant.E_COURSE_FIND);
            jResult.put("msg", "讲座查询失败");
        }
        return jResult.toString();
    }

    @RequestMapping("/modify")
    public String modify(@RequestParam("id") Integer id
            , @RequestParam("datetime") String datetime
            , @RequestParam("title") String title
            , @RequestParam(value = "address", required = false) String address
            , @RequestParam(value = "draft", required = false) Integer draft) {
        JSONObject jResult = new JSONObject();
        try {
            Lecturer lecturer = (Lecturer) httpServletRequest.getSession()
                    .getAttribute(IConstant.KEY_SESSION_USER);
            Course course = new Course();
            course.setId(id);
            course.setTitle(title);
            course.setLecturer(lecturer);
            course.setAddress(address);
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date = dateFormat.parse(datetime);
            course.setDeliveryTime(date);
            course.setDraft((byte) ((null == draft) || (0 == draft) ? 0x0 : 0x1));
            course.setCreateTime(new Date(System.currentTimeMillis()));
            course.setModifyTime(null);

            if (courseService.modify(course)) {
                jResult.put("state", IConstant.SUCCESS);
                jResult.put("msg", "保存成功");
            } else {
                jResult.put("state", IConstant.E_COURSE_MODIFY);
                jResult.put("msg", "保存失败");
            }
        } catch (ParseException e) {
            LOG.error(e.getMessage(), e);
            jResult.put("state", IConstant.E_COURSE_MODIFY);
            jResult.put("msg", "时间无效");
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            jResult.put("state", IConstant.E_COURSE_MODIFY);
            jResult.put("msg", "服务器内部错误，请联系系统管理员");
        }
        return jResult.toString();
    }

    @RequestMapping("/delete")
    public String deleteByLecturer(@RequestParam("id") Integer id) {
        JSONObject jResult = new JSONObject();
        try {
            Lecturer lecturer = (Lecturer) httpServletRequest.getSession()
                    .getAttribute(IConstant.KEY_SESSION_USER);
            Course course = new Course();
            course.setId(id);
            course.setLecturer(lecturer);
            if (courseService.deleteByLecturer(course)) {
                jResult.put("state", IConstant.SUCCESS);
                jResult.put("msg", "删除成功");
            } else {
                jResult.put("state", IConstant.E_COURSE_DELETE);
                jResult.put("msg", "删除失败");
            }
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            jResult.put("state", IConstant.E_COURSE_DELETE);
            jResult.put("msg", "服务器内部错误，请联系系统管理员");
        }
        return jResult.toString();
    }

    @RequestMapping("/findHasCourseDates")
    public String findHasCourseDates(@RequestParam("between") String between
            , @RequestParam("and") String and) {
        JSONObject jResult = new JSONObject();
        LOG.info("between = " + between + ", and = " + and);
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date betweenDate = dateFormat.parse(between);
            Date andDate = dateFormat.parse(and);
            List<Date> dateList = courseService.findHasCourseDates(betweenDate, andDate);
            JSONArray jDateAry = new JSONArray();
            dateList.stream().forEach(e -> {
                jDateAry.put(dateFormat.format(e));
            });
            jResult.put("state", IConstant.SUCCESS);
            jResult.put("dates", jDateAry);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            jResult.put("state", IConstant.E_COURSE_DELETE);
            jResult.put("msg", "服务器内部错误，请联系系统管理员");
        }
        return jResult.toString();
    }

    @RequestMapping("/findHistory")
    public String findHistory() {
        JSONObject jResult = new JSONObject();
        try {
            Lecturer lecturer = null;
            HttpSession session = httpServletRequest.getSession();
            if (null != session) {
                lecturer = (Lecturer) session.getAttribute(IConstant.KEY_SESSION_USER);
            }

            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            List<Course> courseList = courseService.findHistory();
            JSONArray jCourseAry = new JSONArray();
            Lecturer finalLecturer = lecturer;
            courseList.stream().forEach(e -> {
                JSONObject jCourse = new JSONObject();
                jCourse.put("course_id", e.getId());
                jCourse.put("delivery_time", dateFormat.format(e.getDeliveryTime()));
                jCourse.put("lecturer_full_name", e.getLecturer().getFullName());
                jCourse.put("title", e.getTitle());
                jCourse.put("address", e.getAddress());
                if ((null != finalLecturer)
                        && (finalLecturer.getId() == e.getLecturer().getId())) { // 属于当前用户的讲座
                    jCourse.put("allow_edit", true); // 允许编辑
                } else {
                    jCourse.put("allow_edit", false);
                }
                jCourseAry.put(jCourse);
            });
            jResult.put("state", IConstant.SUCCESS);
            jResult.put("courses", jCourseAry);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            jResult.put("state", IConstant.E_COURSE_FIND_HISTORY);
            jResult.put("msg", "服务器内部错误，请联系系统管理员");
        }
        return jResult.toString();
    }
}
